#include "bookdialog.h"
#include "ui_bookdialog.h"
#include <QMessageBox>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlQueryModel>
#include "adminsystem.h"

BookDialog::BookDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::BookDialog)
{
    ui->setupUi(this);

    pageNum = 1;

    model = new QSqlTableModel(this);
    model->setTable("book");
    model->select();
    ui->tableView->setModel(model);
}

BookDialog::~BookDialog()
{
    delete ui;
}

void BookDialog::on_pushButtonAdd_clicked()
{

    if(!ui->lineEditBookId->text().isEmpty() && !ui->lineEditBookName->text().isEmpty()
            && !ui->lineEditAuthor->text().isEmpty() && !ui->lineEditPublish->text().isEmpty()
            && !ui->lineEditBookNum->text().isEmpty())
    {


        QSqlQuery query;
        query.prepare("INSERT INTO book(BookId,BookName,Author,Publish,BookNum)"
                      "VALUES(:BookId, :BookName, :Author, :Publish, :BookNum)");
        query.bindValue(":BookId", ui->lineEditBookId->text());
        query.bindValue(":BookName", ui->lineEditBookName->text());
        query.bindValue(":Author", ui->lineEditAuthor->text());
        query.bindValue(":Publish", ui->lineEditPublish->text());
        query.bindValue(":BookNum", ui->lineEditBookNum->text());
        query.exec();


        ui->lineEditBookId->clear();
        ui->lineEditBookName->clear();
        ui->lineEditAuthor->clear();
        ui->lineEditPublish->clear();
        ui->lineEditBookNum->clear();

        model->select();
        model->submitAll();
    }
    else
    {
        QMessageBox::critical(this,NULL,"Incomplete information");
        return;
    }
}

void BookDialog::on_pushButtonRemove_clicked()
{
    if(ui->lineEditBookIdRemove->text().isEmpty())
    {
        QMessageBox::critical(this,NULL,"BookId is entry");
        return;

    }
    else
    {
        model->setEditStrategy(QSqlTableModel::OnManualSubmit);

        if(QMessageBox::Yes == QMessageBox::warning(this,"Remove row","Really?",QMessageBox::Yes,QMessageBox::No))
        {
            QSqlQuery query;
            query.exec("DELETE FROM book WHERE BookId = ?");
            query.addBindValue(ui->lineEditBookIdRemove->text().toInt());
            query.exec();

            ui->lineEditBookIdRemove->clear();

            model->select();
            model->submitAll();
        }
        else
        {
            ui->lineEditBookIdRemove->clear();
            model->revertAll();
        }
        model->setEditStrategy(QSqlTableModel::OnFieldChange);

    }
}

void BookDialog::on_pushButtonSearch_clicked()
{
    model->setFilter(tr("BookId = '%1'").arg(ui->lineEdit_7->text()));
    ui->lineEdit_7->clear();
    model->select();
    model->submitAll();

}


void BookDialog::on_pushButton_clicked()
{
    close();
}

void BookDialog::on_pushButtonReturnAdminsystem_clicked()
{
    AdminSystem *as = new AdminSystem;
    as->show();
    close();
}
